<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Category;
use app\common\model\Goods;
use app\common\model\Area;
use app\common\model\Address;
use app\common\model\GoodsAttr;
use app\common\model\MoneyLog;
use app\common\model\Order;
use app\common\model\User;
use app\common\model\Cart as cartModel;
use app\common\model\UserCoupon;
use think\Db;
/**
 * 购物车接口
 */
class Cart extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 购物车列表
     * @param string $token  用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1605537209",
    "data": {
    "list": [{
    "id": 2,购物车ID
    "goods_id": 6,商品ID
    "attr_id": 14,规格ID
    "num": 3,数量
    "name": "天然零卡糖",商品名称
    "image": "http:\/\/www.cake.com\/uploads\/20201116\/5268b1414a12bbad4cfb204bc97dd3dd.png",图片
    "attr_name": "8寸",规格名称
    "price": "128.00"单价
    }, {
    "id": 1,
    "goods_id": 6,
    "attr_id": 13,
    "num": 2,
    "name": "天然零卡糖",
    "image": "http:\/\/www.cake.com\/uploads\/20201116\/5268b1414a12bbad4cfb204bc97dd3dd.png",
    "attr_name": "4寸",
    "price": "78.00"
    }],
    "num": 5,购物车商品总数
    "total_price": 540总价
    }
    })
     */
    public function cart_list()
    {
        $token = $this->request->get('token');
        $user = User::where('token',$token)->field('id')->find();
        $list = cartModel::alias('c')->join('goods_attr a','a.id = c.attr_id')->join('goods g','g.id = c.goods_id')->where('c.userid',$user['id'])->field('c.id,c.goods_id,c.attr_id,c.num,g.name,g.image,a.attr_name,a.price')->order('c.id asc')->select();
        $total_price = 0;
        $num = 0;
        foreach($list as &$value){
            $value['image'] = $this->domain.$value['image'];
            $total_price+= $value['price']*$value['num'];
            $num  +=$value['num'];
            $value['is_check'] = false;
        }
        $data = [
            'list'=>$list,
            'num'=>$num,
            'total_price'=>$total_price
        ];
        $this->success($data);
    }
    /**
     * 购物车添加
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $goods_id 商品ID
     * @param string $attr_id 商品规格ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1604476261",
    "data": ""
    })
     */
    public function add_cart()
    {
        $goods_id = $this->request->post('goods_id');
        $attr_id = $this->request->post('attr_id');
        $token = $this->request->post('token');
        $user = User::where('token',$token)->field('id')->find();
        $goods_info =Goods::where('id',$goods_id)->find();
        if($goods_info){
            $attr_info = GoodsAttr::where(['goods_id'=>$goods_info['id'],'id'=>$attr_id])->find();
            if($attr_info){
                $count = cartModel::where(['userid'=>$user['id'],'goods_id'=>$goods_id,'attr_id'=>$attr_id])->count();
                if($count){
                    Db::startTrans();
                    try {
                        $res = cartModel::where(['userid'=>$user['id'],'goods_id'=>$goods_id,'attr_id'=>$attr_id])->setInc('num',1);
                        Db::commit();
                    } catch (Exception $e) {
                        $this->error($e->getMessage());
                        Db::rollback();
                        return false;
                    }

                }else{
                    $data = [
                        'userid'=>$user['id'],
                        'goods_id'=>$goods_id,
                        'attr_id'=>$attr_id,
                        'num'=>1,
                    ];
                    Db::startTrans();
                    try {
                        $res = cartModel::create($data);
                        Db::commit();
                    } catch (Exception $e) {
                        $this->error($e->getMessage());
                        Db::rollback();
                        return false;
                    }
                }
                if($res){
                    $this->success('','操作成功');
                }else{
                    $this->error('操作失败');
                }
            }
        }
        $this->error('商品不存在');

    }
    /**
     * 购物车减少
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $goods_id 商品ID
     * @param string $attr_id 商品规格ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1604476261",
    "data": ""
    })
     */
    public function cut_cart()
    {
        $goods_id = $this->request->post('goods_id');
        $attr_id = $this->request->post('attr_id');
        $token = $this->request->post('token');
        $user = User::where('token',$token)->field('id')->find();
        $goods_info =Goods::where('id',$goods_id)->find();
        if($goods_info){
            $attr_info = GoodsAttr::where(['goods_id'=>$goods_info['id'],'id'=>$attr_id])->find();
            if($attr_info){
                $count = cartModel::where(['userid'=>$user['id'],'goods_id'=>$goods_id,'attr_id'=>$attr_id])->find();
                if($count){
                    Db::startTrans();
                    try {
                        if($count['num'] >1){
                            $res = cartModel::where(['userid'=>$user['id'],'goods_id'=>$goods_id,'attr_id'=>$attr_id])->setDec('num',1);
                        }else{
                            $res = cartModel::where(['userid'=>$user['id'],'goods_id'=>$goods_id,'attr_id'=>$attr_id])->delete();
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        $this->error($e->getMessage());
                        Db::rollback();
                        return false;
                    }

                }else{
                    $res = true;
                }
                if($res){
                    $this->success('','操作成功');
                }else{
                    $this->error('操作失败');
                }
                if($res){
                    $this->success('','操作成功');
                }else{
                    $this->error('操作失败');
                }
            }
        }
    }
    /**
     * 购物车删除
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $cart_id 购物车ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1604476261",
    "data": ""
    })
     */
    public function delete_cart()
    {
        $cart_id = $this->request->post('cart_id');
        $token = $this->request->post('token');
        $user = User::where('token',$token)->field('id')->find();
        $count = cartModel::where(['userid'=>$user['id'],'id'=>$cart_id])->count();
        if($count){
            Db::startTrans();
            try {
                $res = cartModel::where(['userid'=>$user['id'],'id'=>$cart_id])->delete();
                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }

        }else{
            $res = true;
        }
        if($res){
            $this->success('','操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 清空购物车
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1604476261",
    "data": ""
    })
     */
    public function empty_cart()
    {
        $token = $this->request->post('token');
        $user = User::where('token',$token)->field('id')->find();
        $count = cartModel::where('userid',$user['id'])->count();
        if($count == 0){
            $this->error('您的购物车是空的');
        }
        Db::startTrans();
        try {
            $res = cartModel::where(['userid'=>$user['id']])->delete();
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        $this->success('','操作成功');
    }
    /**
     * 购物车结算页面
     * @param string $token 用户token
     * @param string $cart_id 购物车ID,逗号隔开
     * @ApiReturn   ()
     */
    public function confirm_order()
    {
        $token = $this->request->get('token');
        $user_info = User::where('token', $token)->field('id,money')->find();
        $cart_id = $this->request->get('cart_id');
        $list = cartModel::alias('c')->join('goods g','g.id = c.goods_id')->join('goods_attr a','a.id = c.attr_id')->where('c.userid',$user_info['id'])->where('c.id','in',$cart_id)->order('c.id asc')->field('g.name,c.num,a.price')->select();
        if(empty($list)){
            $this->error('请选择商品');
        }
        $goods_names = '';
        $total_price = 0;
        foreach($list as &$value){
            $goods_names .= $value['name'].'、';
            $total_price +=$value['price']*$value['num'];
        }
        $goods_names = rtrim($goods_names,'、');
        //收货地址
        $address = Address::where(['userid' => $user_info['id']])->find();
        if($address){
            $province = Area::where('id',$address['province_id'])->value('name');
            $city = Area::where('id',$address['city_id'])->value('name');
            $area = Area::where('id',$address['area_id'])->value('name');
            $address['address'] = $province.$city.$area.$address['address'];
        }
        //未使用的优惠券查看是否已过期 如果已过期的话把状态改为已过期
        action_coupon();
        //查找优惠券
        $user_coupon = UserCoupon::where('userid', $user_info['id'])->where('status', 0)->field('id,name,discount,type')->order('id asc')->select();
        foreach($user_coupon as &$value1){
            if($value1['type'] == 0){
                $value1['total_price'] = $total_price*$value1['discount']/10;
            }else{
                $value1['total_price'] = $total_price;
            }
        }
        $data = [
            'money'=>$user_info['money'],
            'address'=>$address,
            'goods_name'=>$goods_names,
            'total_price'=>$total_price,
            'coupon_list'=>$user_coupon
        ];
        $this->success($data);
    }
    /**
     * 商品立即购买
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $cart_id 购物车ID,逗号隔开
     * @param string $coupon_id 优惠券ID,没有为0
     * @param string $address_id 收货地址ID
     * @param string $address_type 收货方式0配送1自提
     * @param string $type 支付方式1余额2微信
     * @param string $note 备注
     * @param string $deliverytime 配送时间
     * @ApiReturn   ({
    "code": 200,
    "msg": "支付成功",
    "time": "1605619872",
    "data": {
    "type": 1为1时是余额支付成功，直接跳订单页面，2是调微信支付
    }
    })
     */
    public function buy_now()
    {
        $token = $this->request->post('token');
        $user_info = User::where('token', $token)->field('id,money,openid')->find();
        $coupon_id = $this->request->post('coupon_id');
        $address_id = $this->request->post('address_id');
        $note = $this->request->post('note');
        $type = $this->request->post('type');
        $cart_id = $this->request->post('cart_id');
        $address_type = $this->request->post('address_type');
        $deliverytime = $this->request->post('deliverytime');
        if(!$deliverytime){
            $this->error('请选择配送时间');
        }
       /* if(strtotime($deliverytime) <time()){
            $this->error('选择的配送时间无效');
        }*/
        $goods_info = cartModel::alias('c')->join('goods g','g.id = c.goods_id')->join('goods_attr a','a.id = c.attr_id')->where('c.userid',$user_info['id'])->where('c.id','in',$cart_id)->field('c.id,c.num,g.image,g.name,g.id as goods_id,a.id as attr_id,a.price,a.attr_name')->order('c.id asc')->select();
        if ($goods_info) {
            $total_price = 0;

            foreach ($goods_info as &$value) {
                $total_price +=$value['price']*$value['num'];
                $order_goods[] = [
                    'goods_image'=>$value['image'],
                    'goods_name'=>$value['name'],
                    'attr_name'=>$value['attr_name'],
                    'unit_price'=>$value['price'],
                    'num'=>$value['num'],
                    'createtime'=>time(),
                ];
            }
            //优惠券
            if($coupon_id){
                $coupon_info = UserCoupon::where(['userid'=>$user_info['id'],'status'=>0,'id'=>$coupon_id])->find();
                if(empty($coupon_info)){
                    $this->error('优惠券不存在');
                }
                if($coupon_info['type'] == 0){
                    $actual_price = $total_price*$coupon_info['discount']/10;
                }
            }else{
                $actual_price = $total_price;
            }
            //实际支付金额
            $coupon_money = $total_price - $actual_price;
            //如果是余额支付的话判断余额是否足够
            if($type == 1){
                if($user_info['money'] <$actual_price){
                    $this->error('余额不足');
                }
            }
            if($address_type == 0){
                //如果是配送
                //收货地址
                if($address_id){
                    $address_info  = Address::where(['userid'=>$user_info['id'],'id'=>$address_id])->find();
                    if(empty($address_info)){
                        $this->error('收货地址不存在');
                    }
                }
            }else{
                //如果是自提
                $name = \app\common\model\Config::where('name','name')->value('value');
                $mobile = \app\common\model\Config::where('name','mobile')->value('value');
                $address = \app\common\model\Config::where('name','address')->value('value');
                $address_info = [
                    'username'=>$name,
                    'mobile'=>$mobile,
                    'address'=>$address,
                ];
            }

            //创建订单
            $data = [
                'order_sn'=>'HG'.getOrderSn(),
                'userid'=>$user_info['id'],
                'price'=>$total_price,
                'discounted_price'=>$coupon_money,
                'actual_price'=>$actual_price,
                'username'=>$address_info['username'],
                'mobile'=>$address_info['mobile'],
                'address'=>$address_info['address'],
                'coupon_id'=>$coupon_id,
                'note'=>$note,
                'paytype'=>$type,
                'distribution_type'=>$address_type,
                'deliverytime'=>$deliverytime,
                'createtime'=>time(),
            ];
            Db::startTrans();
            try {
                $res = Order::insertGetId($data);
                if($res){
                    foreach($order_goods as &$v1){
                        $v1['order_id'] = $res;
                    }
                    $res1 = Db::name('order_goods')->insertAll($order_goods);
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($res && $res1){
                if($type == 1){
                    //余额支付
                    Db::startTrans();
                    try {
                        //1.改变订单状态
                        $res2 = Order::where('id',$res)->update(['status'=>1,'paytime'=>time()]);
                        //2.如果使用优惠券的话，改变优惠券状态
                        if($data['coupon_id']){
                            $coupon_info = UserCoupon::where(['userid'=>$user_info['id'],'status'=>0,'id'=>$data['coupon_id']])->find();
                            if($coupon_info){
                                $res3 = UserCoupon::where(['userid'=>$user_info['id'],'status'=>0,'id'=>$data['coupon_id']])->update(['status'=>1]);
                            }
                        }
                        //3.增加余额消费记录
                        $datas = [
                            'userid'=>$user_info['id'],
                            'money'=>$data['actual_price'],
                            'status'=>2
                        ];
                        $res4 = MoneyLog::create($datas);
                        if($res4){
                            $res5 = User::where('id',$user_info['id'])->setDec('money',$data['actual_price']);
                        }
                        Db::commit();
                    } catch (ValidateException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    $result['type'] = 1;
                    $this->success($result,'支付成功');
                }elseif($type ==2){
                    $out_trade_no = $data['order_sn'];
                    $amount =$data['actual_price'];
                    $jsapi = new Response();
                    $result = $jsapi->wx_pay($out_trade_no, $amount, $user_info['openid'],$this->domain . "/api/response/goods_response");
                    $result = json_decode($result,true);
                    $result['type'] = 2;
                    $this->success($result,'请求成功');
                }else{
                    $this->error('支付方式错误');
                }
            }
        }
        $this->error('数据异常');
    }
}
